/*

  Copyright (C) 2020 user18130814200115-2
  Copyright (C) 2021 Kevin "The Nuclear" Bloom <nuclearkev@dragora.org>

  This file is part of libre-bible (LB).

  LB is free software: you can redistribute it and/or modify
  it under the terms of the 2-Clause BSD License.

  LB is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  2-Clause BSD License for more details.

  You should have received a copy of the 2-Clause BSD License
  along with LB.  If not, see <https://opensource.org/licenses/BSD-2-Clause>.

*/

const LOCAL_STORAGE_SESSION_KEY = 'libre-bible-session';
const LOCAL_STORAGE_FAVORITES_KEY = 'libre-bible-favorites';
var Texts = []; //JSON.parse(TextsRaw);
var Chapter = 0;
var Verse = 0;
var NextChapter = 0;
var NextVerse = 0;
var input;
var Book = "Genesis";
var ActiveMenu = null;
var MenuIndex = 0;
var Scroll = 0;
var SelectMode = false;
var ViewFavoriteMode = false;
var SelectedVerses = [];
var OldT = [
  "Genesis",
  "Exodus",
  "Leviticus",
  "Numbers",
  "Deuteronomy",
  "Joshua",
  "Judges",
  "Ruth",
  "1 Samuel",
  "2 Samuel",
  "1 Kings",
  "2 Kings",
  "1 Chronicles",
  "2 Chronicles",
  "Ezra",
  "Nehemiah",
  "Esther",
  "Job",
  "Psalms",
  "Proverbs",
  "Ecclesiastes",
  "Song of Solomon",
  "Isaiah",
  "Jeremiah",
  "Lamentations",
  "Ezekiel",
  "Daniel",
  "Hosea",
  "Joel",
  "Amos",
  "Obadiah",
  "Jonah",
  "Micah",
  "Nahum",
  "Habakkuk",
  "Zephaniah",
  "Haggai",
  "Zechariah",
  "Malachi"
];

const NewT = [
  "Matthew",
  "Mark",
  "Luke",
  "John",
  "Acts",
  "Romans",
  "1 Corinthians",
  "2 Corinthians",
  "Galatians",
  "Ephesians",
  "Philippians",
  "Colossians",
  "1 Thessalonians",
  "2 Thessalonians",
  "1 Timothy",
  "2 Timothy",
  "Titus",
  "Philemon",
  "Hebrews",
  "James",
  "1 Peter",
  "2 Peter",
  "1 John",
  "2 John",
  "3 John",
  "Jude",
  "Revelation"
];

const Apocrypha = [
	"1 Esdras",
	"2 Esdras",
	"Tobit",
	"Judith",
	"Additions to Esther",
	"Wisdom of Solomon",
	"Ecclesiasticus",
	"Baruch",
	"Letter of Jeremiah",
	"Prayer of Azariah",
	"Susanna",
	"Bel and the Dragon",
	"Prayer of Manasseh",
	"1 Maccabees",
	"2 Maccabees"
];

const AllBooks = OldT.concat(NewT.concat(Apocrypha));
const AllSearchOptions = ['query'].concat(AllBooks)
const AllMenuOptions = [
  "Favorites",
  "Increase Font Size",
  "Decrease Font Size",
  "Toggle Theme",
  "Close App"
];
var MenuItems = AllSearchOptions;
var FontSize = 16;

const addScript = (src) => {
  var s = document.createElement( 'script' );
  s.setAttribute( 'src', './assets/js/' + src + '.json' );
  document.body.appendChild( s );
}

const getSession = () => {
  return new Promise((res) => {
    const session = localStorage.getItem(LOCAL_STORAGE_SESSION_KEY);
    if(session) {
      const {
        book,
        chapter,
        scroll,
      } = JSON.parse(session);
	    Book = book;
      Chapter = chapter;
      // Verse = 0;
      Scroll = scroll;
	    addScript(book);
	    setTimeout(() => {
        Texts = JSON.parse(TextsRaw);
        res();
      }, 500);
    } else {
	    addScript(Book);
	    setTimeout(() => {
        Texts = JSON.parse(TextsRaw);
        res();
      }, 500);
    }
  });
};

document.addEventListener("DOMContentLoaded", () => {
	document.getElementById("content").innerHTML = "Loading..."
  getSession().then(() => {
    load({isInit: true});
	  //document.getElementById("verse").focus();
	  // document.getElementById("verse").value = "Genesis:1:1";
    document.getElementById("content").scrollTo(0, Scroll);
	  var displayC = Chapter+1;
	  var display = Verse+1;
    document.getElementById('content').style = "font-size: " + FontSize + "px";
	  document.getElementById("title-text").innerHTML = Book + " " + displayC;
    document.getElementById("left").innerHTML = "Search";
    document.getElementById("middle").innerHTML = "";
    document.getElementById("right").innerHTML = "Menu";
  }).catch(() => {
	  document.getElementById("content").innerHTML = "Failed to load book... :("
  });
});

const clicked = (i, isView = false) => {
  const ref = document.getElementById(i);
  const content = ref.textContent;
  const verse = {
    number: i + 1,
    body: content.slice(1),   // remove verse number
  }
  if(ref.className === "verse") {
    ref.className = "verse active-verse";
    SelectedVerses.push(verse);
  } else {
    ref.className = "verse";
    SelectedVerses.pop(verse);
  }

  if(SelectedVerses.length > 0 && isView) {
    ViewFavoriteMode = true;
    document.getElementById("left").innerHTML = "Share";
    document.getElementById("right").innerHTML = "Cancel";
  } else if(SelectedVerses.length > 0) {
    SelectMode = true;
    document.getElementById("left").innerHTML = "Save";
    document.getElementById("right").innerHTML = "Cancel";
  } else {
    SelectMode = false;
    document.getElementById("left").innerHTML = "Search";
    document.getElementById("right").innerHTML = "Menu";
  }
};

const load = ({
  isInit = false,
  showHighlight = false,
  highlightWaitTime = 1000
}) => {
  const verseList = Texts[Chapter];
  const maxI = verseList.length - 1;
  const entireChapter = verseList.map((v, i) => {
    if(i === maxI) {
      return "";
    }
    return (
      "<div id=\"" + i + "\" class=\"verse\"/><sup>" + (i + 1) + "</sup>" + v + "</div>"
    );
  }).reduce((a, c) => {
    return a + "&#10;" + c;
  }, "");
  const end = "<div id=\"end\" class=\"verse\"></div>";
  // Verse = 0;
	document.getElementById("content").innerHTML = entireChapter.concat([end]);
  // TODO: better way to get the onclick event on the verses.
  // KaiOS blocks the onclick attribute for some reason.
  setTimeout(() => {
    verseList.map((v, i) => {
      if(i !== maxI)
        document.getElementById(i).onclick = function() {clicked(i)};
    });
  }, 500);
	// document.getElementById(Verse).className = "verse active-verse";
  if(!isInit)
	  setTimeout(() => {
      document.getElementById(Verse).scrollIntoView({
        behavor: 'smooth',
        block: 'end',
        inline: 'nearest'
      });
      if(showHighlight) {
        setTimeout(() => {
          document.getElementById(Verse).className = "verse active-verse";
          setTimeout(() => {
            document.getElementById(Verse).className = "verse jumped-to-verse";
          }, highlightWaitTime);
        }, highlightWaitTime)
      }
    }, 100);
  const newSession = JSON.stringify({book: Book, chapter: Chapter});
  localStorage.setItem(LOCAL_STORAGE_SESSION_KEY, newSession);
}

const update = () => {
	var displayC = Chapter+1;
	var display = Verse+1;
	// document.getElementById("verse").value = Book+":"+displayC+":"+display;
	document.getElementById("title-text").innerHTML = Book + " " + displayC;
}

const toggleSearchMenu = (forceUpdate = false) => {
  navigator.spatialNavigationEnabled = false;
  var ref = document.getElementById("search-menu");
	if(ref.className === 'menu menu-active' && !forceUpdate) {
		ref.className = 'menu menu-inactive';
		document.getElementById("search-content").innerHTML = "";
    document.getElementById("left").innerHTML = "Search";
    document.getElementById("right").innerHTML = "Menu";
    document.getElementById("middle").innerHTML = "";
		ActiveMenu = null;
    // MenuItems = AllBooks;
    NextChapter = 0;
    NextVerse = 0;
	} else {
		ref.className = 'menu menu-active';
    if(!forceUpdate)
      MenuItems = AllSearchOptions;
		const menu = MenuItems.reduce((a, b) => {
      const isQuery = b === "query";
      const data = isQuery ? "<div id=\"query-container\"><input id=\"query-textbox\" type=\"text\" placeholder=\"book\"/> <input id=\"query-chap\" type=\"tel\" maxlength=\"2\" placeholder=\"chap.\"/> <input id=\"query-verse\" type=\"tel\" maxlength=\"2\" placeholder=\"verse\"/></div>" : b;
			if(isQuery) {
				return a + "&#10;<div id=\"" + b + "\" class=\"menu-item active\">" + data + "</div>";
			} else {
				return a + "&#10;<div id=\"" + b + "\" class=\"menu-item\">" + data + "</div>";
			}

		}, "");
    MenuIndex = 0;
		document.getElementById("search-content").innerHTML = menu;
    document.getElementById("left").innerHTML = "Back";
    document.getElementById("right").innerHTML = "Current";
    document.getElementById("middle").innerHTML = "SEARCH";
    document.getElementById("query-textbox").focus();
    document.getElementById("query-textbox").scrollIntoView({
      behavor: 'smooth',
      block: 'end',
      inline: 'nearest'
    });
		ActiveMenu = 'search';
	}
};

const toggleMainMenu = () => {
  navigator.spatialNavigationEnabled = false;
  var ref = document.getElementById("main-menu");
	if(ref.className === 'menu menu-active') {
		ref.className = 'menu menu-inactive';
		document.getElementById("main-menu-content").innerHTML = "";
    document.getElementById("left").innerHTML = "Search";
    document.getElementById("right").innerHTML = "Menu";
    document.getElementById("middle").innerHTML = "";
		ActiveMenu = null;
    MenuItems = AllMenuOptions;
	} else {
		ref.className = 'menu menu-active';
    MenuItems = AllMenuOptions;
		const menu = MenuItems.reduce(function(a, b) {
			if(a === '') {
				return a + "&#10;<div id=\"" + b + "\" class=\"menu-item active\">" + b + "</div>";
			} else {
				return a + "&#10;<div id=\"" + b + "\" class=\"menu-item\">" + b + "</div>";
			}

		}, "");
    MenuIndex = 0;
		document.getElementById("main-menu-content").innerHTML = menu;
    document.getElementById("left").innerHTML = "Back";
    document.getElementById("right").innerHTML = "";
    document.getElementById("middle").innerHTML = "SELECT";
    // document.getElementById("query-textbox").focus();
    // document.getElementById("query-textbox").scrollIntoView({
    //   behavor: 'smooth',
    //   block: 'end',
    //   inline: 'nearest'
    // });
		ActiveMenu = 'main';
	}
};

const toggleFavoritesMenu = (forceUpdate = false) => {
  var ref = document.getElementById("favorites-menu");
	if(ref.className === 'menu menu-active' && !forceUpdate) {
		ref.className = 'menu menu-inactive';
		document.getElementById("favorites-menu-content").innerHTML = "";
    document.getElementById("left").innerHTML = "Back";
    document.getElementById("right").innerHTML = "";
    document.getElementById("middle").innerHTML = "SELECT";
		ActiveMenu = "main";
    MenuItems = AllMenuOptions;
    // toggleMainMenu();
	} else {
		ref.className = 'menu menu-active';
    const currentFavorites = JSON.parse(localStorage.getItem(LOCAL_STORAGE_FAVORITES_KEY));
    MenuItems = currentFavorites;
		const menu = MenuItems.reduce(function(a, b) {
			if(a === '') {
				return a + "&#10;<div id=\"" + b + "\" class=\"menu-item active\">" + b + "</div>";
			} else {
				return a + "&#10;<div id=\"" + b + "\" class=\"menu-item\">" + b + "</div>";
			}

 		}, "");
    MenuIndex = 0;
		document.getElementById("favorites-menu-content").innerHTML = menu;
    document.getElementById("left").innerHTML = "Back";
    document.getElementById("right").innerHTML = "Delete";
    document.getElementById("middle").innerHTML = "SELECT";
    // document.getElementById("query-textbox").focus();
    // document.getElementById("query-textbox").scrollIntoView({
    //   behavor: 'smooth',
    //   block: 'end',
    //   inline: 'nearest'
    // });
		ActiveMenu = 'favorites';
	}
}

const loadBook = (b, loadOptions = {}) => {
	Book = b;
  Chapter = NextChapter;
  Verse = NextVerse;
	addScript(b);
	document.getElementById("content").innerHTML = "Loading..."
	setTimeout(() => {  Texts = JSON.parse(TextsRaw); load({});}, 500);
  load(loadOptions);
  update();
};

const saveAndClose = () => {
  const newSession = JSON.stringify({
    book: Book,
    chapter: Chapter,
    scroll: document.getElementById("content").scrollTop,
  });
  localStorage.setItem(LOCAL_STORAGE_SESSION_KEY, newSession);
  close();
}

const createFavorite = () => {
  const verseNumbers = SelectedVerses.map((v) => v.number).sort((a, b) => a > b);
  var ranges = [];
  var currentStart;
  var current;
  var consect = false;
  for(var i = 0; i < verseNumbers.length; i++) {
    const num = verseNumbers[i];
    const isLast = verseNumbers.length - 1 === i;
    if(i === 0) {
      if(isLast) {
        ranges.push([num, null]);
      } else {
        currentStart = num;
        current = num;
      }
    } else if(num - current === 1) {           // consecutive
      current = num;
      consect = true;
      if(isLast)
        ranges.push([currentStart, current]);
    } else if (isLast) {
      if (currentStart === current) {
        ranges.push([current, null]);
      } else {
        ranges.push([currentStart, current]);
      }
      ranges.push([num, null]);
    } else {
      if(consect) {
        ranges.push([currentStart, current]);
      } else {
        ranges.push([currentStart, null]);
      }
      consect = false;
      currentStart = num;
      current = num;
    }
  }
  const versesString = ranges.reduce((a, c) => {
    const [start, end] = c;
    if(a === '') {
      if(end) {
        return start + "-" + end;
      } else {
        return start;
      }
    } else {
      if(end) {
        return a + ", " + start + "-" + end;
      } else {
        return a + "," + start;
      }
    }
  }, '');
  return Book + " " + (Chapter + 1) + ":" + versesString;
};

const navMenu = (dir, menu = 'search') => {
  switch (dir) {
  case 'down': {
    var cur = MenuItems[MenuIndex];
		document.getElementById(cur).className = "menu-item";
		var newMenuIndex = MenuIndex + 1;
    if(newMenuIndex < MenuItems.length) {
      MenuIndex = newMenuIndex;
    } else {
      MenuIndex = 0;
    }
    cur = MenuItems[MenuIndex];
		document.getElementById(cur).className = "active";
		document.getElementById(cur).scrollIntoView({
      behavor: 'smooth',
      block: 'end',
      inline: 'nearest'
    });
    if(cur === 'query') {
      document.getElementById("query-textbox").focus();
      document.getElementById("middle").innerHTML = "SEARCH";
    } else {
      document.getElementById("query-textbox").blur();
      document.getElementById("middle").innerHTML = "SELECT";
    }
    return;
  }
  case 'up': {
		var cur = MenuItems[MenuIndex];
		document.getElementById(cur).className = "menu-item";
		var newMenuIndex = MenuIndex - 1;
    if(newMenuIndex > -1) {
      MenuIndex = newMenuIndex;
    } else {
      MenuIndex = MenuItems.length - 1;
    }
    cur = MenuItems[MenuIndex];
		document.getElementById(cur).className = "active";
		document.getElementById(cur).scrollIntoView({
      behavor: 'smooth',
      block: 'end',
      inline: 'nearest'
    });
    if(cur === 'query') {
      document.getElementById("query-textbox").focus();
      document.getElementById("middle").innerHTML = "SEARCH";
    } else {
      document.getElementById("query-textbox").blur();
      document.getElementById("middle").innerHTML = "SELECT";
    }
    return;
	}
  case 'enter': {
		var s = MenuItems[MenuIndex];
    if(s === "query") {
      const book = document.getElementById("query-textbox").value;
      const chap = document.getElementById("query-chap").value;
      const verse = document.getElementById("query-verse").value;
      if(book === "" && chap === "" && verse === "") {
        MenuItems = AllSearchOptions;
        toggleSearchMenu(true);
      } else if(book === "") {
        if(chap !== '')
          NextChapter = Number(chap) - 1;
        if(verse !== '')
          NextVerse = Number(verse) - 1;
        loadBook(Book, {showHighlight: true, highlightWaitTime: 500});
        toggleSearchMenu();
      } else {
        const queriedBooks = AllBooks.filter((b) =>
          b.toLowerCase().indexOf(book.toLowerCase().trim()) !== -1
        );
        if(chap !== '')
          NextChapter = Number(chap) - 1;
        if(verse !== '')
          NextVerse = Number(verse) - 1;
        MenuItems = ["query"].concat(queriedBooks);
        toggleSearchMenu(true);
        document.getElementById("query-textbox").value = book;
        document.getElementById("query-chap").value = chap;
        document.getElementById("query-verse").value = verse;
        document.getElementById("query-textbox").focus();
        document.getElementById("right").innerHTML = "Clear";
      }
    } else {
      switch (menu) {
      case 'search': {
        loadBook(s, {showHighlight: true});
        toggleSearchMenu();
        return;
      }
      case 'favorites': {
        const [book, chapVerse] = s.split(' ');
        const [chap, verses] = chapVerse.split(':');
        const splitVerses = verses.split(',');
        const verseListUnflattened = splitVerses.map((v) => {
          const range = v.split('-');
          if(range.length > 1) {
            const start = Number(range[0]);
            const end = Number(range[1]);
            const newRange = [];
            for(var i = start; i <= end; i++)  {
              newRange.push(i);
            }
            return newRange;
          } else {
            return range;
          }
        });
        const verseList = [].concat.apply([], verseListUnflattened).sort((a, b) => a > b);
        NextChapter = Number(chap) - 1;
        NextVerse = Number(verseList[0]) - 1;
        loadBook(book, {showHighlight: false})
	      setTimeout(() => {
          verseList.map((v) => {
            clicked(v - 1, true);
          });
        }, 700);
        toggleFavoritesMenu();
        toggleMainMenu();
        return;
      }
      case 'main': {
        const id = document.getElementById(s).id;
        switch (id) {
        case 'Favorites': {
          toggleFavoritesMenu();
          return;
        }
        case 'Increase Font Size': {
          const newFontSize = FontSize + 2;
          if(newFontSize < 30) {
            FontSize = newFontSize;
            document.getElementById('content').style = "font-size: " + FontSize + "px";
          }
          toggleMainMenu();
          return;
        }
        case 'Decrease Font Size': {
          const newFontSize = FontSize - 2;
          if(newFontSize > 5) {
            FontSize = newFontSize;
            document.getElementById('content').style = "font-size: " + FontSize + "px";
          }
          toggleMainMenu();
          return;
        }
        case 'Close App': {
          toggleMainMenu();
          saveAndClose();
          return;
        }
        case 'Toggle Theme': {
          toggleMainMenu();
          return;
        }
        }
        return;
      }
      }
    }
    return;
	}
  // This one is sort of specific for the search menu
  case 'clear-query': {
    var ref = document.getElementById("query-textbox");
    if(ref.value !== "") {
      ref.value = "";
      // MenuItems = AllBooks;
      toggleSearchMenu(true);
      document.getElementById("right").innerHTML = "";
      MenuIndex = 0;
    } else {
			var cur = MenuItems[MenuIndex];
			document.getElementById(cur).className = "menu-item";
			var newMenuIndex = MenuItems.findIndex((b) => Book === b);
      MenuIndex = newMenuIndex;
      cur = MenuItems[MenuIndex];
			document.getElementById(cur).className = "menu-item active";
			document.getElementById(cur).scrollIntoView({
        behavor: 'smooth',
        block: 'end',
        inline: 'nearest'
      });
      if(cur === 'query') {
        document.getElementById("query-textbox").focus();
        document.getElementById("middle").innerHTML = "SEARCH";
      } else {
        document.getElementById("query-textbox").blur();
        document.getElementById("middle").innerHTML = "SELECT";
      }
	  }
    return;
  }
  }
};

document.addEventListener("keydown", (e) => {
  e.preventDefault();
	// console.log(e.key);
  switch (e.key) {
  case "Backspace": {
    if(ActiveMenu === 'main') {
        toggleMainMenu();
    } else if (ActiveMenu === 'search') {
      toggleSearchMenu();
    } else {
      if(confirm("Close app?"))
        saveAndClose();
    }
    return;
  }
  case "Enter": {
    navMenu('enter', ActiveMenu)
    return;
  }
  case "ArrowUp": {
    if (ActiveMenu) {
      navMenu('up');
    } else {
      document.getElementById('content').scrollBy({
        top: -100,
        left: 0,
        behavor: 'smooth',
      });
    }
    return;
  }
  case "ArrowDown": {
    if (ActiveMenu) {
			navMenu('down');
	  } else {
      document.getElementById('content').scrollBy({
        top: 100,
        left: 0,
        behavor: 'smooth',
      });
    }
    return;
  }
  case "ArrowLeft": {
    if(ActiveMenu) {
      if(document.activeElement.id === "query-textbox") {
        document.getElementById("query-textbox").blur();
        document.getElementById("query-verse").focus();
      } else if(document.activeElement.id === "query-verse") {
        document.getElementById("query-verse").blur();
        document.getElementById("query-chap").focus();
      } else {
        document.getElementById("query-chap").blur();
        document.getElementById("query-textbox").focus();
      }
    } else {
      if(Chapter > 0) {
		    document.getElementById(Verse).className = "verse";
        Chapter -= 1;
        Verse = 0;
        load({showHighlight: false});
		    update();
      } else {
		    document.getElementById(Verse).className = "verse";
        Chapter = 0;
        Verse = 0;
        const i = AllBooks.findIndex((b) => Book === b) - 1;
        if(i > 0) {
          loadBook(AllBooks[i], {showHighlight: false});
        } else {
          loadBook(AllBooks[AllBooks.length - 1], {showHighlight: false});
        }
      }
    }
    return;
  }
  case "ArrowRight": {
    if(ActiveMenu) {
      if(document.activeElement.id === "query-textbox") {
        document.getElementById("query-textbox").blur();
        document.getElementById("query-chap").focus();
      } else if(document.activeElement.id === "query-chap") {
        document.getElementById("query-chap").blur();
        document.getElementById("query-verse").focus();
      } else {
        document.getElementById("query-verse").blur();
        document.getElementById("query-textbox").focus();
      }

    } else {
      const end = Texts.length - 1;
      if(Chapter < end) {
		    document.getElementById(Verse).className = "verse";
        Chapter += 1;
        Verse = 0;
		    load({showHighlight: false});
		    update();
      } else {
		    document.getElementById(Verse).className = "verse";
        Chapter = 0;
        Verse = 0;
        const i = AllBooks.findIndex((b) => Book === b) + 1;
        if(i < AllBooks.length - 1) {
          loadBook(AllBooks[i], {showHighlight: false});
        } else {
          loadBook(AllBooks[0], {showHighlight: false});
        }
      }
    }
    return;
  }
  case "SoftLeft": {
    if(SelectMode) {
      const favorite = createFavorite();
      const currentFavorites = JSON.parse(localStorage.getItem(LOCAL_STORAGE_FAVORITES_KEY));
      const hasFavoriteAlready = currentFavorites.filter((f) => f === favorite);
      if(hasFavoriteAlready.length > 0) {
        // TODO: display error about no duplicate favorites
      } else {
        const favorites = currentFavorites ? currentFavorites.concat([favorite]) : [favorite];
        localStorage.setItem(LOCAL_STORAGE_FAVORITES_KEY, JSON.stringify(favorites));
        SelectedVerses.map(({number}) => {
          document.getElementById(number - 1).className = "verse";
        });
        SelectMode = false;
        SelectedVerses = [];
        document.getElementById("left").innerHTML = "Search";
        document.getElementById("right").innerHTML = "Menu";
      }
    } else if(ViewFavoriteMode) {
      // TODO: add sharing code
    } else {
      if(ActiveMenu === 'main') {
        toggleMainMenu();
      } else if(ActiveMenu === 'favorites') {
        toggleFavoritesMenu();
      } else {
		    toggleSearchMenu();
      }
    }
    return;
  }
  case "SoftRight": {
    if(SelectMode) {
      document.getElementById("left").innerHTML = "Search";
      document.getElementById("right").innerHTML = "Menu";
      SelectedVerses.map(({number}) => {
        document.getElementById(number - 1).className = "verse";
      });
      SelectMode = false;
      SelectedVerses = [];
    } else if (ViewFavoriteMode) {
      document.getElementById("left").innerHTML = "Search";
      document.getElementById("right").innerHTML = "Menu";
      SelectedVerses.map(({number}) => {
        document.getElementById(number - 1).className = "verse";
      });
      ViewFavoriteMode = false;
      SelectedVerses = [];
    } else {
      if(ActiveMenu === 'search') {
        navMenu('clear-query');
      } else if(ActiveMenu === 'favorites') {
        const currentFavorites = JSON.parse(localStorage.getItem(LOCAL_STORAGE_FAVORITES_KEY));
        const selected = MenuItems[MenuIndex];
        const withoutSelected = currentFavorites.filter((fav) => fav !== selected);
        localStorage.setItem(LOCAL_STORAGE_FAVORITES_KEY, JSON.stringify(withoutSelected));
        toggleFavoritesMenu(true);
      } else {
        toggleMainMenu();
      }
    }
    return;
  }
  case "1": {
    const e = document.getElementById(document.activeElement.id);
    e.value = e.value + 1;
    return;
  }
  case "2": {
    if(ActiveMenu) {
      const e = document.getElementById(document.activeElement.id);
      e.value = e.value + 2;
    } else {
      navigator.spatialNavigationEnabled = !navigator.spatialNavigationEnabled;
    }
    return;
  }
  case "3": {
    const e = document.getElementById(document.activeElement.id);
    e.value = e.value + 3;
    return;
  }
  case "4": {
    const e = document.getElementById(document.activeElement.id);
    e.value = e.value + 4;
    return;
  }
  case "5": {
    const e = document.getElementById(document.activeElement.id);
    e.value = e.value + 5;
    return;
  }
  case "6": {
    const e = document.getElementById(document.activeElement.id);
    e.value = e.value + 6;
    return;
  }
  case "7": {
    const e = document.getElementById(document.activeElement.id);
    e.value = e.value + 7;
    return;
  }
  case "8": {
    const e = document.getElementById(document.activeElement.id);
    e.value = e.value + 8;
    return;
  }
  case "9": {
    const e = document.getElementById(document.activeElement.id);
    e.value = e.value + 9;
    return;
  }
  case "0": {
    const e = document.getElementById(document.activeElement.id);
    e.value = e.value + 0;
    return;
  }
 }
});
